<template>
    <div class="app-container">
        <el-card shadow="always">
            <el-form :model="queryParams" :inline="true" label-width="150px" class="main_form">
                <el-form-item label="工单来源">
                    <el-select v-model="queryParams.source" placeholder="请选择" clearable>
                        <el-option label="10086投诉" value="10086投诉"></el-option>
                        <el-option label="内部投诉" value="内部投诉"></el-option>
                        <el-option label="低满修复" value="低满修复"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否延期">
                    <el-select v-model="queryParams.isDelayed" placeholder="请选择" clearable>
                        <el-option label="是" value="是"></el-option>
                        <el-option label="否" value="否"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="EOMS单号">
                    <el-input v-model="queryParams.eomsId" clearable></el-input>
                </el-form-item>
                <el-form-item label="客服流水号">
                    <el-input v-model="queryParams.serialNo" clearable></el-input>
                </el-form-item>
                <el-form-item label="客户投诉工单号">
                    <el-input v-model="queryParams.customerComplaintOrderNo" clearable></el-input>
                </el-form-item>
                <el-form-item label="业务">
                    <el-input v-model="queryParams.business" clearable></el-input>
                </el-form-item>
                <el-form-item label="投诉区县" prop="county">
                    <el-select v-model="queryParams.county" placeholder="请选择" clearable>
                        <el-option v-for="dict in nhp_county_type_short" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="投诉地址" v-show="showSearch">
                    <el-input v-model="queryParams.complaintAddress" clearable></el-input>
                </el-form-item>
                <el-form-item label="受理号码" v-show="showSearch">
                    <el-input v-model="queryParams.serviceNumber" clearable></el-input>
                </el-form-item>
                <el-form-item label="工单当前状态" v-show="showSearch">
                    <el-select v-model="queryParams.orderCurrentState" placeholder="请选择" clearable>
                        <el-option label="已完成" value="已完成"></el-option>
                        <el-option label="专家组处理" value="专家组处理"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="当前处理人" v-show="showSearch">
                    <el-input v-model="queryParams.currentHandler" clearable></el-input>
                </el-form-item>
                <el-form-item label="剩余时间" v-show="showSearch">
                    <el-input v-model="queryParams.remainingTime" clearable></el-input>
                </el-form-item>
                <el-form-item label="派单时间" v-show="showSearch">
                    <el-date-picker v-model="dispatchTime" value-format="YYYY-MM-DD" type="daterange"
                        start-placeholder="开始日期" end-placeholder="结束日期" clearable
                        style="width: 408px;"></el-date-picker>
                </el-form-item>
                <el-form-item label="要求回复时间" v-show="showSearch">
                    <el-date-picker v-model="requiredResponseTime" value-format="YYYY-MM-DD" type="daterange"
                        start-placeholder="开始日期" end-placeholder="结束日期" clearable
                        style="width: 408px;"></el-date-picker>
                </el-form-item>
                <el-form-item label="测试工单号" v-show="showSearch">
                    <el-input v-model="queryParams.testOrderNo" clearable></el-input>
                </el-form-item>
                <!-- <el-form-item label="测试子状态" v-show="showSearch">
                    <el-select v-model="queryParams.testSubStatus" placeholder="请选择" clearable>
                        <el-option label="待测试" value="待测试"></el-option>
                        <el-option label="测试中" value="测试中"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="子工单状态" v-show="showSearch">
                    <el-select v-model="queryParams.subOrderState" placeholder="请选择" clearable>
                        <el-option label="处理中" value="处理中"></el-option>
                        <el-option label="已处理" value="已处理"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="处理结果" v-show="showSearch">
                    <el-input v-model="queryParams.processingResult" clearable></el-input>
                </el-form-item>
                <el-form-item label="新客服流水号" v-show="showSearch">
                    <el-input v-model="queryParams.newCustomerServiceSerialNo" clearable></el-input>
                </el-form-item> -->
                <el-form-item label="工单标题" v-show="showSearch">
                    <el-input v-model="queryParams.orderTitle" clearable></el-input>
                </el-form-item>
                <el-form-item label="是否重复投诉" v-show="showSearch">
                    <el-select v-model="queryParams.isDuplicateComplaint" placeholder="请选择" clearable>
                        <el-option label="是" value="是"></el-option>
                        <el-option label="否" value="否"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否重复派单" v-show="showSearch">
                    <el-select v-model="queryParams.isDuplicateDispatch" placeholder="请选择" clearable>
                        <el-option label="是" value="是"></el-option>
                        <el-option label="否" value="否"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="投诉性质" v-show="showSearch">
                    <el-select v-model="queryParams.complaintType" placeholder="请选择" clearable>
                        <el-option label="普通投诉" value="普通投诉"></el-option>
                        <el-option label="其他" value="其他"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="专家组处理-处理人">
                    <el-select v-model="queryParams.expertGroupHandler" placeholder="请选择" clearable>
                        <el-option v-for="dict in expertGroupHandlerOptions" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="专家组处理-处理结果">
                    <!-- multiple -->
                    <el-select v-model="queryParams.expertGroupProcessingResult" placeholder="请选择" clearable multiple>
                        <el-option label="解决但未经测试确认" value="解决但未经测试确认"></el-option>
                        <el-option label="延期解决" value="延期解决"></el-option>
                        <el-option label="无法解决" value="无法解决"></el-option>
                        <el-option label="解决并经现场测试确认恢复" value="解决并经现场测试确认恢复"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="原因分类">
                    <!-- multiple -->
                    <el-select v-model="queryParams.reasonOpinion" placeholder="请选择" clearable multiple>
                        <el-option v-for="dict in closureOpinion" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="方案是否完成">
                    <el-select v-model="queryParams.planCompletedStatus" placeholder="请选择" clearable>
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="Search" @click="queryListTable">查询</el-button>
                    <el-button @click="unsetQueryForm"><el-icon>
                            <RefreshRight />
                        </el-icon>重置</el-button>

                    <!-- <el-button type="primary" icon="Search" @click="weiChartApi1">查询延期表需要插入优化单号的工单</el-button> -->
                    <!-- <el-button type="primary" icon="Search" @click="weiChartApi2">将用户的聊天内容插入延期表</el-button> -->
                    <!-- <el-button type="primary" icon="Search" @click="weiChartApi3">截止时间3小时推送</el-button> -->
                    <!-- <el-button type="primary" icon="Search" @click="weiChartApi4">查询延期未完成工单</el-button> -->
                </el-form-item>

                <right-toolbar v-model:showSearch="showSearch" @queryTable="queryListTable"
                    style="position: absolute;right: 0;bottom: 10px;"></right-toolbar>
            </el-form>
        </el-card>

        <el-card shadow="always" style="margin-top: 10px; min-height: 500px; padding-bottom: 20px">
            <el-row>
                <el-button type="primary" icon="Download" @click="handleDataExport">导出</el-button>
            </el-row>
            <div id="table" style="margin-top: 20px">
                <el-table v-loading="loading" ref="qualityTable" :data="tableData" style="width: 100%"
                    @sort-change="sortChange" @filter-change="filterChange">
                    <el-table-column prop="source" label="工单来源" width="120px"></el-table-column>
                    <el-table-column prop="eomsId" label="EOMS单号" width="200px"></el-table-column>
                    <el-table-column prop="dispatchTime" label="派单时间" width="165px"></el-table-column>
                    <el-table-column prop="county" label="工单归属区县" width="120px"></el-table-column>
                    <el-table-column prop="orderTitle" label="工单标题" width="350px"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column prop="complaintAddress" label="投诉标准地址" width="220px"></el-table-column>
                    <el-table-column prop="expertGroupHandler" label="专家组处理-处理人" width="180px"></el-table-column>
                    <el-table-column prop="expertGroupProcessingResult" label="专家组处理-处理结果"
                        width="220px"></el-table-column>
                    <el-table-column prop="reasonOpinion" label="原因分类" width="220px"></el-table-column>
                    <el-table-column prop="planCompletedStatus" label="方案是否完成" width="120px"></el-table-column>
                    <el-table-column prop="expertGroupReasonCategory" label="专家组处理-问题原因分类"
                        width="220px"></el-table-column>
                    <el-table-column prop="expertGroupSupplementary" label="专家组处理-补充说明" width="220px"
                        show-overflow-tooltip>
                    </el-table-column>

                    <el-table-column prop="complaintType" label="投诉性质"></el-table-column>
                    <el-table-column prop="complaintTime" label="投诉时间" width="165px"></el-table-column>
                    <el-table-column prop="orderId" label="工单唯一标识" width="176px"></el-table-column>
                    <!-- 解决措施分类测试 -->
                    <!-- <el-table-column prop="analysisSolutionCategory" label="测试-综合分析-解决措施分类"
                        width="176px"></el-table-column>
                    <el-table-column prop="expertGroupSolutionCategory" label="测试-专家组处理-解决措施分类"
                        width="176px"></el-table-column> -->
                    <!-- <el-table-column prop="expectedResolveTime" label="延期时间-测试"></el-table-column> -->
                    <!-- <el-table-column prop="closureOpinion" label="报结意见-测试"></el-table-column> -->
                    <!-- <el-table-column prop="expertGroupImplementationStatus" label="专家组处理-实施状态-测试"
                        width="220px"></el-table-column> -->
                    <el-table-column prop="networkType" label="网络制式"></el-table-column>
                    <el-table-column prop="complaintBusiness" label="投诉业务"></el-table-column>
                    <el-table-column label="工单状态" width="200px">
                        <template #default="scope">
                            <!-- expertGroupProcessingResult为延期解决的时候,显示数据 -->
                            <!-- {{ scope.row.isNeedUpdate }} -->
                            <!-- {{ scope.row.closureOpinion }} -->
                            <div v-if="scope.row.expertGroupProcessingResult === '延期解决'">
                                <!-- 后端逻辑判断是否需要更新 -->
                                <!-- 如果需要更新,表示需要点击详情去生成一条延期记录 -->
                                <el-tag v-if="scope.row.isNeedUpdate" type="warning">{{
                                    scope.row.expertGroupProcessingResult }}-待延期</el-tag>
                                <el-tag v-else type="success">延期解决 - 已延期</el-tag>
                            </div>
                            <span v-else>{{ scope.row.expertGroupProcessingResult }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="serialNo" label="客服流水号" width="200px"></el-table-column> -->
                    <!-- <el-table-column prop="customerComplaintOrderNo" label="客户投诉工单号" width="200px"></el-table-column> -->
                    <el-table-column prop="business" label="业务"></el-table-column>
                    <el-table-column label="受理号码" width="120px">
                        <template #default="scope">
                            <el-tooltip :content="scope.row.serviceNumber" placement="top">
                                <!-- 取前三位和后四位 -->
                                <span>{{ scope.row.serviceNumber.slice(0, 3) + '****' +
                                    scope.row.serviceNumber.slice(-4) }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column prop="orderCurrentState" label="工单当前状态" width="120px"></el-table-column>
                    <el-table-column prop="currentHandler" label="当前处理人" width="120px"></el-table-column>
                    <el-table-column prop="requiredResponseTime" label="要求回复时间" width="165px"></el-table-column>
                    <el-table-column prop="remainingTime" label="剩余时间" width="165px"></el-table-column>
                    <el-table-column prop="isDelayed" label="是否延期"></el-table-column>
                    <el-table-column prop="testOrderNo" label="测试工单号" width="120px"></el-table-column>
                    <el-table-column prop="testSubStatus" label="测试子状态" width="165px"></el-table-column>
                    <el-table-column prop="subOrderState" label="子工单状态" width="165px"></el-table-column>
                    <!-- <el-table-column prop="processingResult" label="处理结果"></el-table-column> -->
                    <!-- <el-table-column prop="newCustomerServiceSerialNo" label="新客服流水号" width="165px"></el-table-column> -->
                    <el-table-column prop="isDuplicateComplaint" label="是否重复投诉" width="120px"></el-table-column>
                    <el-table-column prop="isDuplicateDispatch" label="是否重复派单" width="120px"></el-table-column>
                    <el-table-column fixed="right" label="操作" align="center" min-width="100">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="fnOpenDialog(scope.row)">详情</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty :image-size="40" />
                    </template>
                </el-table>
                <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                    @pagination="queryListTable" :autoScroll="false" />
            </div>
        </el-card>

        <Detail ref="refDetail" @saveSuccess="queryListTable" />

        <export-dialog ref="refExportDialog" @directExport="directExportData"
            :serviceName="'NetworkQualityServiceImpl.exportQualityData'" :type="'网络质量数据导出'" />
    </div>
</template>

<script setup name="networkQuality">
import { ref } from "vue";
import * as complainApi from "@/api/complain/complain";
import { useConfigStore } from "@/store/modules/config.js";
import { Plus } from '@element-plus/icons-vue';
import Detail from "./components/detail.vue";
import { getClosureOpinion } from './components/mappingUtils.js';

const closureOpinion = getClosureOpinion()

const { proxy } = getCurrentInstance();

const { nhp_network_type, nhp_county_type_short, nhp_closure_opinion } = proxy.useDict("nhp_network_type", "nhp_county_type_short", "nhp_closure_opinion");

const configStoreData = useConfigStore();
let securityFlagConfig = configStoreData.configList.filter(
    (item) => item.configKey === "sys.securityFlag"
)[0];

const options = [
    {
        key: "是",
        value: "是"
    },
    {
        key: "否",
        value: "否"
    },
]

let expertGroupHandlerOptions = ref([]);

const weiChartApi1 = () => {
    console.log("weiChartApi1");
    complainApi.queryComplaintDelayOperationIsNeedOptimizeOrderId(queryParams.value).then((res) => {
        console.log(res);
    })
}

/* const resolveChartData = (input) => {
    const lines = input.split('\n');
    const result = [];

    let current = {};

    lines.forEach(line => {
        const [key, value] = line.split(': ').map(s => s.trim());
        const fieldMap = {
            'eoms工单号': 'eomsId',
            '优化单号': 'optimizeOrderId'
        };

        if (fieldMap[key]) {
            current[fieldMap[key]] = value;
        }

        // 检查是否已经处理完一个完整的记录（即已经包含了eomsId和optimizeOrderId）
        if (key === '优化单号' && current['eomsId'] && current['optimizeOrderId']) {
            result.push(current);
            current = {}; // 重置current对象，为下一个记录做准备
        }
    });

    return result;
}; */

/* const weiChartApi2 = () => {
    console.log("weiChartApi2");
    // let str = `
    // eoms工单号: ZJ-0612-20250517-00710
    // 区县: 宁海
    // 方案类型：规划
    // 站点名称：宁波宁海下洋涂2NR.
    // 解决情况：延期解决
    // 满意情况: 不确定
    // 优化工单号: dddxxxx
    // 方案是否完成：否
    // 是否需要再次方案：是
    // 是否有再次方案：是
    // 是否完成：否
    // 处理过程：
    //     九级地址：宁海县长街镇宁海通用航空机场【任何地方信号都不好，拒绝提供详细地址111】
    //     涉及站点：宁波宁海下洋涂2NR
    //     涉及方案：规划
    //     用户反映5G问题，由于用户所在区域超出5G覆盖原因导致，计划通过规划新站解决，加上观察，故申请延期至6月30日完成，用户认可。（已知弱覆盖：ZJ-0612-20250517-00710）
    // `

    // let str2 = `
    // eoms工单号: ZJ-0612-20250517-00710
    // 优化单号: dddxxxx
    // 满意情况: 不确定1
    // 方案类型：规划 1
    // 方案是否完成：否
    // 是否需要再次方案：是
    // 区县：宁海 1

    // eoms工单号: ZJ-0612-20250517-00719
    // 优化单号: dddxx2443322
    // `

    let str3 = `
    eoms工单号: ZJ-0612-20250618-00443
    优化单号: 3333333
    `

    // console.log(str2);
    complainApi.updateComplaintDelayOperationByWeChat(str3).then((res) => {
        console.log(res);
        // proxy.$modal.msgSuccess("提交成功");
    })
} */

/* const weiChartApi3 = () => {
    console.log("weiChartApi3");
    complainApi.queryComplaintDelay3Hover(queryParams.value).then((res) => {
        console.log(res);
    })
} */
/* const weiChartApi4 = () => {
    console.log("weiChartApi4");
    complainApi.queryComplaintDelayNotCompletedTip(queryParams.value).then((res) => {
        console.log(res);
    })
} */


let dispatchTime = ref([])  // 派单时间
let requiredResponseTime = ref([])  // 要求回复时间
let loading = ref(false);

const refExportDialog = ref(null);

const queryParams = ref({
    eomsId: "ZJ-0612-20250618-00443"
});

const nowSortContent = ref();
const nowOrder = ref();

const tableData = ref([]);
const detailData = ref([]);

const pageSize = ref(10);
const currentPage = ref(1);
const total = ref(0);

const showSearch = ref(true);

const refDetail = ref(null);

const nowStatus = ref();

// 重置
function unsetQueryForm() {
    queryParams.value = {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
    };
    queryListTable()
}

const getParams = () => {
    let params = JSON.parse(JSON.stringify(queryParams.value))

    // 数组转字符串
    params.expertGroupProcessingResult = params.expertGroupProcessingResult?.join(',')
    params.reasonOpinion = params.reasonOpinion?.join(',')

    return {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
        ...params,
        dispatchTimeStart: JSON.stringify(dispatchTime.value) === '[]' || !dispatchTime.value ? undefined : dispatchTime.value[0],
        dispatchTimeEnd: JSON.stringify(dispatchTime.value) === '[]' || !dispatchTime.value ? undefined : dispatchTime.value[1],
        requiredResponseTimeStart: JSON.stringify(requiredResponseTime.value) === '[]' || !requiredResponseTime.value ? undefined : requiredResponseTime.value[0],
        requiredResponseTimeEnd: JSON.stringify(requiredResponseTime.value) === '[]' || !requiredResponseTime.value ? undefined : requiredResponseTime.value[1],
    }
}

function queryListTable() {
    loading.value = true;
    complainApi.queryCompliantAranList(getParams()).then((res) => {
        loading.value = false;
        tableData.value = res.rows;
        total.value = res.total;
    });
}

// 分数排序
function sortChange(column, prop, order) {
    nowSortContent.value = column.prop;
    nowOrder.value = column.order;
    // console.log(nowSortContent.value, nowOrder.value);
    queryListTable();
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数
    const day = date.getDate().toString().padStart(2, "0"); // 使用 padStart 来确保日期是两位数
    return `${year}-${month}-${day}`;
}

// 筛选状态
function filterChange(filters) {
    queryListTable();
}

// 打开详情页
function fnOpenDialog(row) {
    // console.log(row);
    refDetail.value.show(row);
}

function exportData(name) {
    let param = getParams()
    param.sortContent = nowSortContent.value;
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    proxy.download(
        "/complaint/exportCompliantAranList",
        {
            ...param,
        },
        `${name}_${new Date().getTime()}.xlsx`
    );
}

function handleDataExport() {
    if (securityFlagConfig.configValue == "true") {
        let param = getParams()
        param.sortContent = nowSortContent.value;
        param.order = nowOrder.value;
        param.status = nowStatus.value;
        //开启金库模式
        refExportDialog.value.show(param);
    } else {
        exportData("诉中管控查询");
    }
}

function directExportData() {
    exportData("诉中管控查询(剔除敏感数据)");
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) {
        return;
    }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day;
    return formattedDateTimeString;
}

const init = () => {
    complainApi.queryCompliantAranExpertGroupHandler().then((res) => {
        res.data.forEach(item => {
            expertGroupHandlerOptions.value.push({
                key: item,
                value: item
            });
        })
    })
    queryListTable();
}

init();
</script>

<style scoped>
.main_form {
    position: relative;
}
</style>
